import classNames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import Icon from '../Icon/index'
import styles from './index.module.scss'

const Image = ({ src, className, alt }) => {
  //记录图片加载是否出错
  const [isError, setisError] = useState(false)
  //记录图片是否正在加载的状态
  const [isLoading, setisLoading] = useState(true)

  //对图片元素的引用
  const imgRef = useRef(null)
  useEffect(() => {
    const observer = new IntersectionObserver(([{ isIntersecting }]) => {
      if (isIntersecting) {
        // console.log(isIntersecting)
        //图片在可视区
        imgRef.current.src = imgRef.current.dataset.src
        //取消监听
        observer.unobserve(imgRef.current)
      }
    })
    observer.observe(imgRef.current)
  }, [])
  return (
    <div className={classNames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}
      {isLoading && (
        <div className='image-icon'>
          <Icon type='icon-24gl-pictures'></Icon>
        </div>
      )}
      {/*     加载出错时 */}
      {isError && (
        <div className='image-icon'>
          <Icon type='icon-24gl-pictureSplit'></Icon>
        </div>
      )}
      {/* 加载成功时显示的内容 */}
      {!isError && (
        <img
          data-src={src}
          alt={alt}
          ref={imgRef}
          onLoad={() => {
            setisError(false)
            setisLoading(false)
          }}
          onError={() => {
            setisLoading(false)
            setisError(true)
          }}
        />
      )}
    </div>
  )
}

export default Image
